<template>
  <div class="user-profile-page">
    <!-- 顶部：用户信息区 -->
    <section class="profile-header">
      <div class="header-content">
        <!-- 头像 -->
        <a-avatar
          :size="80"
          :src="loginUserStore.loginUser.userAvatar"
          class="profile-avatar"
        >
          <template v-if="!loginUserStore.loginUser.userAvatar">
            {{ loginUserStore.loginUser.userName?.charAt(0)?.toUpperCase() || 'U' }}
          </template>
        </a-avatar>
        <!-- 用户名和角色 -->
        <div class="username-row">
          <h2 class="username">{{ loginUserStore.loginUser.userName || '未登录' }}</h2>
          <a-tag 
            v-if="loginUserStore.loginUser.userRole === 'admin'"
            color="green"
            class="role-tag"
          >
            管理员
          </a-tag>
          <a-tag 
            v-else
            color="blue"
            class="role-tag"
          >
            普通用户
          </a-tag>
        </div>

        <!-- 个人简介 -->
        <div class="bio">
          <span v-if="loginUserStore.loginUser.userProfile">
            {{ loginUserStore.loginUser.userProfile }}
          </span>
          <span v-else class="bio-placeholder">
            快来丰富你的个人介绍吧~
          </span>
          <EditOutlined class="edit-icon" @click="editUserInfo" />
        </div>
      </div>
    </section>

    <!-- 导航标签 -->
    <section class="nav-tabs">
      <div class="tabs-container">
        <div class="tab-item active">
          <span>作品</span>
          <div class="tab-indicator"></div>
        </div>
      </div>
    </section>

    <!-- 作品列表区 -->
    <section class="works-section">
      <div class="works-container">
        <div class="card-grid" v-if="hasMyApps">
          <div
            v-for="item in myPage.records"
            :key="item?.id"
            class="card-hover"
          >
            <a-card
              hoverable
              class="app-card"
            >
              <template #cover>
                <img
                  :alt="item?.appName || 'cover'"
                  :src="item?.cover || defaultCover"
                />
              </template>
              <a-card-meta
                :title="item?.appName || '未命名应用'"
                :description="`创建于 ${formatDate(item?.createTime, 'YYYY-MM-DD')}`"
              />
            </a-card>
            
            <!-- 查看对话、查看作品遮罩 -->
            <div
              v-if="item?.deployKey || item?.id"
              class="hover-actions"
            >
              <a-button
                v-if="item?.deployKey"
                class="btn btn-dark"
                size="large"
                @click.stop="viewWork(item)"
              >
                查看作品
              </a-button>
              <a-button
                v-if="item?.id"
                class="btn btn-light"
                size="large"
                @click.stop="viewChat(item?.id)"
              >
                查看对话
              </a-button>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-tip">
          暂无作品，试试在主页上方的输入框中描述你的想法，开始创建吧～
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="hasMyApps">
          <a-pagination
            :current="myQuery.pageNum || 1"
            :page-size="myQuery.pageSize || 8"
            :total="myPage.totalRow || 0"
            show-size-changer
            @change="onMyPageChange"
            @showSizeChange="onMyPageChange"
          />
        </div>
      </div>
    </section>

    <!-- 编辑用户信息弹窗 -->
    <EditUserInfoModal
      v-model:open="editModalVisible"
      :user-info="loginUserStore.loginUser"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { EditOutlined } from '@ant-design/icons-vue'
import { listMyAppVoByPage } from '@/api/appController.ts'
import { formatDate } from '@/utils/FormatDate'
import { useLoginUserStore } from '@/stores/LoginUserStore'
import { useRouter } from 'vue-router'
import { getDeployUrl } from '@/config/env.ts'
import EditUserInfoModal from '@/components/EditUserInfoModal.vue'

// 默认封面图
const defaultCover = 'https://zero-code-generator-1332372410.cos.ap-guangzhou.myqcloud.com/empty-image/empty.png'

// 路由
const router = useRouter()

// 登录用户 store
const loginUserStore = useLoginUserStore()

// 我的作品分页与数据
const myQuery = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 8,
  sortField: 'createTime',
  sortOrder: 'desc'
})

const myPage = reactive<API.PageAppVO>({
  records: [],
  pageNumber: 1,
  pageSize: 8,
  totalPage: 0,
  totalRow: 0
})

const myLoading = ref(false)

// 加载"我的作品"
const loadMyApps = async () => {
  try {
    myLoading.value = true
    const res = await listMyAppVoByPage({ ...myQuery })
    if (res.data.code == 0 && res?.data.data) {
      myPage.records = res.data.data.records
      myPage.totalRow = res.data.data.totalRow
      myPage.totalPage = res.data.data.totalPage
    }
  } catch (e) {
    message.error('加载我的作品失败')
  } finally {
    myLoading.value = false
  }
}

// 分页事件
const onMyPageChange = (page: number, size: number) => {
  myQuery.pageNum = page
  myQuery.pageSize = size
  loadMyApps()
}

// 查看对话
const viewChat = (appId: string | number | undefined) => {
  if (appId) {
    router.push(`/app/chat/${appId}?view=1`)
  }
}

// 查看作品（当应用已被成功部署后，即deployKey参数不为空）
const viewWork = (app: API.AppVO) => {
  if (app.deployKey) {
    const url = getDeployUrl(app.deployKey)
    window.open(url, '_blank')
  }
}

// 编辑用户信息弹窗控制
const editModalVisible = ref(false)

// 编辑用户信息
const editUserInfo = () => {
  editModalVisible.value = true
}

onMounted(() => {
  // 确保获取最新的登录用户信息
  loginUserStore.fetchLoginUser()
  loadMyApps()
})

const hasMyApps = computed(() => (myPage.records?.length || 0) > 0)
</script>

<style scoped>
/* 让布局的主内容背景透明 */
:deep(.main-content) {
  background: transparent !important;
}

/* 全屏渐变背景，铺满整个视口 */
.user-profile-page {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  /* 品牌蓝绿竖向渐变（上白下蓝），贴近示例图 */
  background: linear-gradient(
    180deg,
    #ffffff 0%,
    #f5f7f7 3%,
    #f9fcfc 5%,
    #f3f7f8 8%,
    #f0f8f9 15%,
    #e8fbff 26%,
    #b8f4f2 38%,
    #7fdde8 58%,
    #59bfe6 75%,
    #25baf5 86%,
    #3f8fe0 100%
  );
  background-attachment: fixed;
}

/* 顶部用户信息区 */
.profile-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 20px 10px;
}

.header-content {
  text-align: center;
  max-width: 980px;
  width: 100%;
}

.profile-avatar {
  margin-bottom: 16px;
  border: 3px solid #ffffff;
  box-shadow: 0 4px 12px rgba(15, 23, 42, 0.1);
}

.username-row {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  gap: 12px;
  margin-bottom: 8px;
}

.username {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #0f172a;
}

.role-tag {
  margin: 0;
  margin-top: 6px;
}

.bio {
  margin-top: 16px;
  color: #475569;
  font-size: 14px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.bio-placeholder {
  color: #94a3b8;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.edit-icon {
  font-size: 15px;
  margin-left: 10px;
  opacity: 0.6;
  cursor: pointer;
  transition: opacity 0.2s ease;
}

.edit-icon:hover {
  opacity: 1;
}

/* 导航标签区 */
.nav-tabs {
  display: flex;
  justify-content: center;
  padding: 0 20px;
}

.tabs-container {
  display: flex;
  gap: 32px;
  max-width: 1100px;
  width: 100%;
  justify-content: center;
}

.tab-item {
  position: relative;
  padding: 12px 0;
  cursor: pointer;
  color: #64748b;
  font-size: 15px;
  font-weight: 500;
  transition: color 0.2s ease;
}

.tab-item.active {
  color: #0f172a;
}

.tab-item.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #25baf5, #3f8fe0);
  border-radius: 2px 2px 0 0;
}

/* 作品列表区 */
.works-section {
  display: flex;
  justify-content: center;
  padding: 24px 20px 48px;
}

.works-container {
  width: 100%;
  max-width: 1100px;
  background: #ffffff;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 12px 32px rgba(15, 23, 42, 0.06);
}

/* 我的作品卡片样式 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
  margin-top: 15px;
}

.app-card {
  border-radius: 12px;
  overflow: hidden;
  padding: 0;
}

/* 作品卡片封面等比裁剪 */
.app-card :deep(.ant-card-cover) {
  overflow: hidden;
  border-bottom: 1px solid #f1f5f9;
}

.app-card :deep(.ant-card-cover img) {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
}

/* 紧凑卡片样式 */
.app-card :deep(.ant-card-body) {
  padding: 10px;
}

.app-card :deep(.ant-card-meta-title) {
  margin-bottom: 6px;
  font-size: 14px;
}

.app-card :deep(.ant-card-meta-description) {
  margin-top: 0;
  font-size: 12px;
  color: #64748b;
}

/* 悬浮操作层 */
.card-hover {
  position: relative;
}

.hover-actions {
  position: absolute;
  border-radius: 12px;
  inset: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: center;
  justify-content: center;
  background: rgba(15, 23, 42, 0.35);
  opacity: 0;
  visibility: hidden;
  transition: opacity .2s ease, visibility .2s ease;
  padding: 12px;
  z-index: 2;
}

.card-hover:hover .hover-actions {
  opacity: 1;
  visibility: visible;
}

/* 按钮风格 */
.hover-actions .btn {
  height: 44px;
  padding: 0 22px;
  border-radius: 999px;
  font-weight: 600;
  box-shadow: 0 8px 20px rgba(15,23,42,0.15);
  cursor: pointer;
  transition: transform .15s ease, box-shadow .15s ease, filter .15s ease;
}

.hover-actions .btn:hover {
  transform: translateY(-1px) scale(1.02);
  box-shadow: 0 10px 24px rgba(15,23,42,0.22);
}

.hover-actions .btn-dark {
  background: #0f172a;
  color: #fff;
  border: none;
}

.hover-actions .btn-dark:hover {
  background: #111827;
  color: #fff;
}

.hover-actions .btn-light {
  background: #fff;
  color: #0f172a;
  border: none;
}

.hover-actions .btn-light:hover {
  background: #f8fafc;
  color: #0f172a;
}

.empty-tip {
  text-align: center;
  padding: 48px 20px;
  color: #94a3b8;
  font-size: 14px;
}

/* 分页器 */
.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .card-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 640px) {
  .card-grid {
    grid-template-columns: 1fr;
  }
  
  .tabs-container {
    gap: 16px;
  }
  
  .tab-item {
    font-size: 14px;
  }
}
</style>
